package moltencore.network.protocol;

import spark.math.Vector2;
import spark.network.Util;

import java.nio.ByteBuffer;

import moltencore.game.bubble.Type;
import moltencore.game.bubble.Bubble;

public class BubbleData {
	private long fieldId;
	private static final int FIELD_ID_LENGTH = Long.SIZE / 8;
	private short bubbleId;
	private static final int BUBBLE_ID_LENGTH = Short.SIZE / 8;
	private Vector2 position;
	private static final int POSITION_LENGTH = Vector2.SIZE / 8;
	private Vector2 velocity;
	private static final int VELOCITY_LENGTH = Vector2.SIZE / 8;
	private Type type;
	private static final int TYPE_LENGTH = Byte.SIZE / 8;

	public static final int SIZE =
			FIELD_ID_LENGTH +
			BUBBLE_ID_LENGTH +
			POSITION_LENGTH +
			VELOCITY_LENGTH +
			TYPE_LENGTH;

	public BubbleData() {
	}

	public BubbleData(Bubble bubble, long fieldId) {
		this.bubbleId = bubble.getBubbleId();
		this.fieldId = fieldId;
		this.position = bubble.getPosition();
		this.type = bubble.getType();
		this.velocity = bubble.getVelocity();
	}

	public long getFieldId() {
		return fieldId;
	}

	public void setFieldId(long fieldId) {
		this.fieldId = fieldId;
	}

	public short getBubbleId() {
		return bubbleId;
	}

	public void setBubbleId(short bubbleId) {
		this.bubbleId = bubbleId;
	}

	public Vector2 getPosition() {
		return position;
	}

	public void setPosition(Vector2 position) {
		this.position = position;
	}

	public Vector2 getVelocity() {
		return velocity;
	}

	public void setVelocity(Vector2 velocity) {
		this.velocity = velocity;
	}

	public Type getType() {
		return type;
	}

	public void setType(Type type) {
		this.type = type;
	}

	public void getBytes(byte[] buffer, int offset) {
		ByteBuffer bb = ByteBuffer.wrap(buffer, offset, buffer.length - offset);
		bb.putLong(fieldId);
		bb.putShort(bubbleId);
		bb.put(Util.makeBytes(position));
		bb.put(Util.makeBytes(velocity));
		bb.put(type.toByte());
	}

	public void fill(byte[] buffer, int offset) {
		ByteBuffer bb = ByteBuffer.wrap(buffer, offset, buffer.length - offset);
		fieldId = bb.getLong();
		bubbleId = bb.getShort();
		byte[] vector2 = new byte[8];
		bb.get(vector2);
		position = Util.makeVector2(vector2, 0);
		bb.get(vector2);
		velocity = Util.makeVector2(vector2, 0);
		type = Type.fromByte(bb.get());
	}

	public int getSize() {
		return SIZE;
	}
}
